// 请求工具类
class Request {
  constructor() {
    this.baseURL = 'http://localhost:9205'
    this.timeout = 10000
  }

  // 请求拦截器
  interceptRequest(options) {
    // 添加token
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }
    
    // 添加基础URL
    if (!options.url.startsWith('http')) {
      options.url = this.baseURL + options.url
    }
    
    return options
  }

  // 响应拦截器
  interceptResponse(response) {
    const { statusCode, data } = response
    
    if (statusCode === 200) {
      return data
    } else if (statusCode === 401) {
      // token过期，清除本地存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('userId')
      uni.removeStorageSync('phone')
      uni.removeStorageSync('expiresIn')
      uni.removeStorageSync('isNewUser')
      
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login'
      })
      
      return Promise.reject(new Error('登录已过期，请重新登录'))
    } else {
      return Promise.reject(new Error(data.msg || '请求失败'))
    }
  }

  // 通用请求方法
  request(options) {
    return new Promise((resolve, reject) => {
      const requestOptions = this.interceptRequest({
        timeout: this.timeout,
        ...options
      })
      
      uni.request({
        ...requestOptions,
        success: (response) => {
          try {
            const result = this.interceptResponse(response)
            resolve(result)
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          reject(new Error('网络请求失败'))
        }
      })
    })
  }

  // GET请求
  get(url, data = {}) {
    return this.request({
      url,
      method: 'GET',
      data
    })
  }

  // POST请求
  post(url, data = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      header: {
        'Content-Type': 'application/json'
      }
    })
  }

  // PUT请求
  put(url, data = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      header: {
        'Content-Type': 'application/json'
      }
    })
  }

  // DELETE请求
  delete(url, data = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data
    })
  }
}

// 创建实例
const request = new Request()

// 导出
export default request